<script lang="ts" setup>
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { useFs } from '@fast-crud/fast-crud';
import { Button } from 'ant-design-vue';

import { SopIsvInfoApi } from '#/api/devOperation/sop/sopIsvInfo';
import { downloadByData } from '#/utils/file/download';

import { createCrudOptions, downloadTemplate } from './data/keys';

defineOptions({
  name: '设置秘钥',
  inheritAttrs: false,
});
const { crudBinding } = useFs({ createCrudOptions });

const formRef = ref();

function handleDownloadIsvKey() {
  const form = formRef.value.getFormData();

  const text = downloadTemplate
    .replace('{appId}', form.appId)
    .replace('{privateKeyIsv}', form.privateKeyIsv)
    .replace('{publicKeyPlatform}', form.publicKeyPlatform);

  downloadByData(text, `${form.appId}_秘钥_${Date.now()}.txt`);
}

const [Modal, modalApi] = useVbenModal({
  showConfirmButton: false,
  async onOpened() {
    const isvId = modalApi.getData()?.isvId;

    const form = await SopIsvInfoApi.getKeys(isvId);

    formRef.value.setFormData(form, { mergeForm: false });
  },
});
defineExpose(modalApi);
</script>

<template>
  <Modal title="查看秘钥" class="w-[60%]">
    <div class="common-form">
      <FsForm ref="formRef" v-bind="crudBinding.viewForm" mode="view" />
    </div>
    <template #prepend-footer>
      <Button type="primary" @click="handleDownloadIsvKey">
        下载开发者秘钥
      </Button>
    </template>
  </Modal>
</template>
